package com.awphone.controller;

import com.awphone.listener.ServletContextListenerImpl;
import com.google.gson.JsonObject;
import org.apache.log4j.Logger;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;

/**
 * @author a_polyakov
 */
public abstract class AbstractController extends HttpServlet {

    private EntityManagerFactory entityManagerFactory;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        entityManagerFactory = ServletContextListenerImpl.getEntityManagerFactory();
    }

    @Override
    protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
        long time = System.currentTimeMillis();
        Writer writer = null;
        EntityManager entityManager = null;
        try {
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            entityManager = entityManagerFactory.createEntityManager();
            execute(entityManager, request, response);
//		} catch (UnauthorizedException e) {
//			response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
//			response.setContentType("text/plain");
//			writer.write(e.getMessage());
//			getLog().error("Error doPost", e);
//		} catch (NullPointerException e) {
//			response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
//			response.setContentType("text/plain");
//			e.printStackTrace(new PrintWriter(writer));
//			getLog().error("Error doPost", e);
        } catch (Exception e) {
//			response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
//			response.setContentType("text/plain");
//			writer.write(e.getMessage());
            getLog().error("Error doPost", e);
        } finally {
            if (entityManager != null && entityManager.isOpen()) {
                final EntityTransaction transaction = entityManager.getTransaction();
                if (transaction != null && transaction.isActive()) {
                    transaction.rollback();
                }
                entityManager.close();
            }
            time = System.currentTimeMillis() - time;
            getLog().debug(time + " ms");
        }
    }

    protected final Logger getLog() {
        return Logger.getLogger(this.getClass());
    }

    protected abstract JsonObject execute(final EntityManager entityManager, final HttpServletRequest request, final HttpServletResponse response) throws Exception;
}
